const gulp = require('gulp')
var rename = require('gulp-rename')
var gap = require('gulp-append-prepend')

let postcssConfig = require('./postcss.config')
let postcssPlugins = []
if (postcssConfig.plugins) {
  for (let pluginName in postcssConfig.plugins) {
    postcssPlugins.push(
      require(pluginName)(postcssConfig.plugins[pluginName]),
    )
  }
}

let fs = require('fs')

let postcssPt = require('./tools/postcss/pt/index')

// https://regexr.com/456er
let resolvePrefixerRegexp = /@prefixer\s+([^\{])+\s+\{([^\/]*)\/\*\s*@endprefixer\s*\*\/[^\}]*\}/g

let postcssPrefixer = require('./tools/postcss/prefixer/index')

let postcss = require('gulp-postcss')

let replace = require('gulp-replace')

let JSON5 = require('gulp-json5-posix')

const Path = require('path')

let postFileTasks = {}

let wxssFiles = [
  './dist/app.less.wxss',
  './dist/app.scss.wxss',
  // './dist/app.prefix,less.wxss',
  // './dist/app.prefix.scss.wxss',
]

let postcssFile = function (src, postConfig = {}, dest = 'dist') {
  if (src.indexOf('prefix') > -1) {
    return gulp
      .src(src)
      .pipe(
        postcss(
          postcssPlugins.concat([
            postcssPrefixer({
              prefix: 'a',
              ignore: [/van-/, /a-/, /u-/, /mt-/, '.ignore'],
            }),
          ])
          , postConfig))
      .pipe(replace(resolvePrefixerRegexp, function (match, $1, $2) {
        console.warn('$1', $1)
        return `/* @prefixer ${$1} */
` + $2.trim() + `
/* @endprefixer */
`
      }))
      .pipe(gulp.dest(dest))
  }
  return gulp
    .src(src)
    .pipe(postcss(
      postcssPlugins.concat([]),
    ))
    .pipe(gulp.dest(dest))
}

let postcssFileTask = function (src, postConfig = {}, dest = 'dist') {
  return gulp.task(src, function () {
    return postcssFile(src, postConfig, dest)
  })
}

let startWatchFileTask = function (watch, task = []) {
  gulp.watch(watch, task)
}

// wxssFiles.forEach(function (wxssFileSrc) {
//   let _n = 'compile:' + wxssFileSrc
//   postFileTasks[_n] = {
//     taskName: _n,
//     src: wxssFileSrc,
//     task: postcssFileTask(wxssFileSrc),
//   }
// })

gulp.task('replace:index.js', async function () {
  let appModule = require('./template/app')

  function removeIndex() {
    let p = require('path').join(__dirname,  'dist/index.js')
    if (fs.existsSync(p)) {
      fs.unlinkSync(p)
    }
  }

  console.log('call index build')

  return gulp
    .src('./dist/index.js')
    .on('end', function () {
      console.log('build end')
      removeIndex()
    })
    .pipe(gap.prependText(appModule.bef))
    .pipe(
      rename(function (path) {
        path.basename = 'app'
      }),
    )
    .pipe(gulp.dest('./dist'))

})

gulp.task('transform:project.config.json', async function () {
  gulp
    .src('./src/project.config.json')
    .pipe(gulp.dest('./dist'))
    .on('end', function () {
      console.log('transform project.config.json')
    })
})

gulp.task('transform:dist:project.config.json', async function () {
  gulp
    .src('./dist/project.config.json')
    .pipe(gulp.dest('./src'))
    .on('end', function () {
      console.log('transform dist:project.config.json')
    })
})

gulp.task('transform:_package.json', async function () {
  gulp
    .src('./src/_package.json')
    .pipe(
      rename(function (p) {
        p.basename = 'package'
      }),
    )
    .pipe(gulp.dest('./dist'))
    .on('end', function () {
      console.log('transform _package.json')
    })
})

gulp.task('compile:./tmp/app.less.wxss', async function () {
  return postcssFile('./tmp/app.less.wxss', {}, 'dist')
})

gulp.task('compile:./tmp/app.scss.wxss', async function () {
  return postcssFile('./tmp/app.scss.wxss', {}, 'dist')
})

gulp.task('compile:./tmp/app.prefix.less.wxss', async function () {
  return postcssFile('./tmp/app.prefix.less.wxss', {}, 'dist')
})

gulp.task('compile:./tmp/app.prefix.scss.wxss', async function () {
  return postcssFile('./tmp/app.prefix.scss.wxss', {}, 'dist')
})

gulp.task('compile:app.wxss', async function () {
  gulp
    .src('./src/app.wxss')
    .pipe(postcss())
    .pipe(gap.prependText(`
@import "app.less.wxss";
@import "app.scss.wxss";
@import "app.prefix.less.wxss";
@import "app.prefix.scss.wxss";
@import "app.prefix.wxss";
    `))
    .pipe(gulp.dest('./dist'))
})

gulp.task('compile:app.prefix.wxss', async function () {
  postcssFile('./src/app.prefix.wxss')
})

gulp.task('trans:app.js', async function () {
  let appModule = require('./template/app')

  console.log('trans:app.js')
  gulp.src('./src/app.js')
    .pipe(gap.prependText(appModule.bef))
    .pipe(gulp.dest('./dist'))
})

gulp.task('trans:static', async function () {
  gulp.src('./src/static/**/*')
    .pipe(gulp.dest('./dist/static'))
})

gulp.task('trans:miniprogram_npm', async function () {
  gulp.src('./src/miniprogram_npm/**/*')
    .pipe(gulp.dest('./dist/miniprogram_npm'))
})

gulp.task('trans:behaviors', async function () {
  gulp.src('./src/behaviors/**/*.js')
    .pipe(gulp.dest('./dist/behaviors'))
})

gulp.task('trans:components:wxml', async function () {
  gulp.src('./src/components/**/*.wxml')
    .pipe(gulp.dest('./dist/components'))
})

gulp.task('trans:pages:wxs', async function () {
  gulp.src('./src/pages/**/*.wxs')
    .pipe(gulp.dest('./dist/pages'))
})

gulp.task('trans:tmp:wxml', async function () {
  gulp.src('./tmp/**/*.wxml')
    .pipe(gulp.dest('./dist'))
})

gulp.task('trans:components:js', async function () {
  gulp.src('./src/components/**/*.js')
    .pipe(gulp.dest('./dist/components'))
})

gulp.task('trans:vendors', async function () {
  gulp.src('./src/vendors/**/*')
    .pipe(gulp.dest('./dist/vendors'))
})


gulp.task('init:w', gulp.series(
  'compile:app.prefix.wxss',
  'trans:vendors',
  'trans:app.js',
  'trans:static',
  'trans:miniprogram_npm',
  'compile:./tmp/app.less.wxss',
  'compile:./tmp/app.scss.wxss',
  'compile:./tmp/app.prefix.less.wxss',
  'compile:./tmp/app.prefix.scss.wxss',
  'trans:components:wxml',
  'trans:components:js',
  'trans:pages:wxs',
  'compile:app.wxss',
))

gulp.task('trans:json', async function () {
  initDetectJSON('src/**/index.json',
    {base: 'src'},'dist', )
})

function initDetectJSON(src, options, dist, watch = src) {
  gulp.src(src, options)
    .pipe(JSON5({
      beautify: true // default
    }))
    .pipe(gulp.dest(dist))

  if (watch) {
    let watcher = gulp.watch(watch, function() {

    })
    watcher.on('change', function(path, stats) {
      // if (event.type === 'added') {
      //   // ...
      // } else if (event.type === 'deleted') {
      //   // ...
      // }
      gulp.src(src, options)
      .pipe(JSON5({
        beautify: true // default
      }))
      .pipe(gulp.dest(dist))
    })
  }
}

gulp.task('w', gulp.series(
  'transform:project.config.json',
  'trans:json',
  'transform:_package.json',
  function () {
    console.log('start gulp watch')

    gulp.watch('./src/app.js', gulp.series('trans:app.js'))
    gulp.watch('./src/static/**/*', gulp.series('trans:static'))
    gulp.watch('./src/miniprogram_npm/**/*', gulp.series('trans:miniprogram_npm'))
    gulp.watch('./src/behaviors/**/*', gulp.series('trans:behaviors'))
    gulp.watch('./src/components/**/*.wxml', gulp.series('trans:components:wxml'))
    gulp.watch('./src/components/**/*.js', gulp.series('trans:components:js'))
    gulp.watch('./src/pages/**/*.wxs', gulp.series('trans:pages:wxs'))

    gulp.watch('./dist/project.config.json', gulp.series('transform:dist:project.config.json'))

    gulp.watch('./tmp/app.less.wxss', gulp.series('compile:./tmp/app.less.wxss'))
    gulp.watch('./tmp/app.scss.wxss', gulp.series('compile:./tmp/app.scss.wxss'))
    gulp.watch('./tmp/app.prefix.less.wxss', gulp.series('compile:./tmp/app.prefix.less.wxss'))
    gulp.watch('./tmp/app.prefix.scss.wxss', gulp.series('compile:./tmp/app.prefix.scss.wxss'))

    gulp.watch('./tmp/**/*.wxml', gulp.series('trans:tmp:wxml'))

    // gulp.watch('./dist/index.js', gulp.series('replace:index.js'))
    gulp.watch('./src/app.wxss', gulp.series('compile:app.wxss'))
    gulp.watch('./src/app.prefix.wxss', gulp.series('compile:app.prefix.wxss'))
    gulp.watch('./src/_package.json', gulp.series('transform:_package.json'))
  }
))
